import { defineStore } from 'pinia'
import { Profile } from '@/types/user'
import { IResponse } from '@/types/data'
import request from '@/utils/request'
import { setProfile, getProfile, removeProfile } from '@/utils/storage'
import useStore from '..'

export default defineStore('user', {
  state: () => ({
    profile: getProfile()
  }),
  actions: {
    async login({ account, password }: { account: string, password: string }) {
      const r = await request.post<IResponse<Profile>>('/login', {
        account,
        password
      })
      this.profile = r.data.result
      setProfile(r.data.result)
    },
    // 获取手机验证码
    async sendMobileMsg(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    // 短信登录
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<IResponse<Profile>>('/login/code', {
        mobile,
        code
      })
      this.profile = res.data.result
    },
    // 退出
    logout() {
      this.profile = {} as Profile
      removeProfile()
      const { cart } = useStore()
      cart.clearCart()
    },
    //  source: 1 为 pc，2 为 webapp，3 为微信小程序, 4 为 Android, 5 为 ios, 6 为 qq, 7 为微信
    async qqLogin(openId: string) {
      const res = await request.post<IResponse<Profile>>('/login/social', {
        unionId: openId,
        source: 6
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 绑定 QQ 的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<IResponse<Profile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId
      })
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 无账号发送验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile
        }
      })
    },
    //注册&绑定
    async qqPatchLogin(data: any) {
      const res = await request.post<IResponse<Profile>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    }
  }
})